﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WSManager.Wpf
{
    static class Extensions
    {
        public static CategoryViewModel FindCategory(this IEnumerable<CategoryViewModel> categories, string id, StringComparison options = StringComparison.InvariantCulture)
        {
            CategoryViewModel item = null;

            foreach (var cat in categories)
            {
                if (cat.Category.Id.Equals(id, options))
                {
                    item = cat;
                    break;
                }
                item = cat.Subcategories.FindCategory(id, options);
                if (item != null)
                    break;
            }

            return item;
        }

        public static IEnumerable<CategoryViewModel> Recursive(this IEnumerable<CategoryViewModel> categories)
        {
            return categories.SelectMany(c => new[] {c}.Concat(c.Subcategories.Recursive()));
        }

        public static IEnumerable<T> Log<T>(this IEnumerable<T> coll, string message, Func<T, object> logItem = null)
        {
            if (logItem == null) logItem = x => x;
            var list = coll.ToList();
            var sb = new StringBuilder();
            sb.AppendFormat("logging collection of {0}; {1}", typeof (T).Name, message);
            foreach (var item in list)
            {
                sb.AppendFormat("\n   {{{0} => {1}}}", item, logItem(item));
            }
            Debug.Write(sb + "\n");
            return list;
        }

        public static TValue ValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key)
        {
            if (dic.ContainsKey(key)) return dic[key];
            return default(TValue);
        }
    }
}
